package com.seawaterbt.springbootshiro.realm;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.seawaterbt.springbootshiro.entity.Permission;
import com.seawaterbt.springbootshiro.entity.Role;
import com.seawaterbt.springbootshiro.entity.User;
import com.seawaterbt.springbootshiro.service.UserService;
import com.seawaterbt.springbootshiro.utils.ShiroUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /** 授权 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //System.out.println("权限配置 --> ShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principalCollection.getPrimaryPrincipal();
        List<Role> roleList = userService.selectAllRole(user);
        List<Permission> permissionList = userService.selectAllPermissionByUid(user);
        if(!roleList.isEmpty()){
            roleList.forEach(e->{
                authorizationInfo.addRole(e.getRid().toString());
            });
        }
        if(!permissionList.isEmpty()){
            permissionList.forEach(e->{
                authorizationInfo.addStringPermission(e.getPermissionCode());
            });
        }
        return authorizationInfo;
    }

    /** 认证 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String)authenticationToken.getPrincipal();
        User user = userService.selectOne(new EntityWrapper<User>().eq("username", username));
        if(Objects.isNull(user)){
            return null;
        }
        if(user.getStatus() == 2){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),this.getName());
        return authenticationInfo;
    }
}
